package org.example.guava;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.Collection;
import java.util.List;

/**
 * @Classname GuavaFilter
 * @Description guavafilter
 * @Date 2020/12/21 3:16 下午
 * @Created by xiangjd
 */
public class GuavaFilter {

    @Test
    public void test1() {
        List<String> list = Lists.newArrayList("tom", "jerry", "Joah", "jack");
        Iterable<String> result = Iterables.filter(list, Predicates.containsPattern("j"));
        Collection<String> result1 = Collections2.filter(list, Predicates.containsPattern("o"));
        //找出包含J字母或不包含a的元素
        Collection<String> result2 = Collections2.filter(list,
                Predicates.or(Predicates.containsPattern("J"),
                        Predicates.not(Predicates.containsPattern("a"))));
        System.out.println(result);
        System.out.println(result1);
        System.out.println(result2);

        List<String> names = Lists.newArrayList("John", null, "Jane", null, "Adam", "Tom");
        //去掉包含null的元素
        Collection<String> result3 = Collections2.filter(names, Predicates.notNull());
        // [John, Jane, Adam, Tom]
        System.out.println(result3);

        //检查一个collection中的所有元素是否符合某个条件：
        List<String> names1 = Lists.newArrayList("John", "Jane", "Adam", "Tom");
        boolean result4 = Iterables.all(names1, Predicates.containsPattern("n|m"));
        // true
        System.out.println(result4);
        result4 = Iterables.all(names1, Predicates.containsPattern("a"));
        // false
        System.out.println(result4);
    }

    @Test
    public void test2() {
        List<Integer> collections = Lists.newArrayList(1, 2, 3, 4);
        Collection<Integer> filter = Collections2.filter(
                collections, new Predicate<Integer>() {
                    @Override
                    public boolean apply(Integer input) {
                        return input >= 3;
                    }
                });
        // [3, 4]
        System.out.println(filter);
    }

    /**
     * 需要说明的是每次调用返回都是新的对象，同时操作过程不是线程安全的。
     */
    @Test
    public void test3() {
        List<Integer> list = Lists.newArrayList(1, 2, 3, 4);
        List<String> transform = Lists.transform(list, new Function<Integer, String>() {
            @Override
            public String apply(Integer integer) {
                return integer + "_test";
            }
        });
        System.out.println(transform);
    }
}
